//
//  AppDelegate.m
//  PropertyMananger
//
//  Created by bh on 16/12/20.
//  Copyright © 2016年 BH. All rights reserved.
//

#import "AppDelegate.h"
#import "BHMainTabbarController.h"
#import "LoginViewController.h"
#import "GuidePagesView.h"

//极光推送
#import "JPUSHService.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>
#import "AppDelegate+JPush.h"

//秒兜
static NSString * miaoDouKey = @"a2043cbb0b364891829be3cff579cd1e";

@interface AppDelegate ()<JPUSHRegisterDelegate>

@property (nonatomic,strong)  LoginViewController * loginVc;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    self.loginVc = [[LoginViewController alloc]init];
    self.window.rootViewController = self.loginVc;
    
    [self.window makeKeyAndVisible];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(returnLoginVc:) name:exsitLoginNoticeCenter object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSucess:) name:@"loginSucessNotification" object:nil];
    
    //引导页
    [self setGuiderVC];
    
    // 配置IQKeyboardManager
    [self configurationIQKeyboard];
    
    //极光推送
    [self setJPUSWithApplication:application Options:launchOptions];
    
    //设置秒都
    [self confirmMiaoDou];
    
    return YES;
}
- (void)confirmMiaoDou{

    [[MDManager sharedManager] initBlue];
    
    [[MDManager sharedManager] setAppKey:miaoDouKey];

}
-(void)setRoot{
    
    BHMainTabbarController * tabbarVC = [[BHMainTabbarController alloc]init];
    self.window.rootViewController = tabbarVC;

}
//返回登录界面
- (void)returnLoginVc:(NSNotification *)notic
{
//    LoginViewController * loginVc = [[LoginViewController alloc]init];
    self.window.rootViewController = self.loginVc;
}
- (void)loginSucess:(NSNotification *)noti
{
    
    
    BHMainTabbarController * tabbarVC = [[BHMainTabbarController alloc]init];
    self.window.rootViewController = tabbarVC;
   
}
#pragma mark - 引导页
- (void)setGuiderVC
{
    //只运行一次
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *launched = [userDefaults objectForKey:@"launched"];
    
        if (!launched)
        {
            [self guidePages];
            launched = @"YES";
            [userDefaults setObject:launched forKey:@"launched"];
            [userDefaults synchronize];
        }
    

}
- (void)guidePages
{
    //数据源
    NSArray *imageArray = @[@"工单", @"查询", @"记录", @"摇一摇"];
    
    //  初始化方法1
    GuidePagesView *guiderVC = [[GuidePagesView alloc] init];
    guiderVC.imageDatas = imageArray;
    __weak typeof(GuidePagesView) *weakSelf = guiderVC;
    guiderVC.buttonAction = ^{
        [UIView animateWithDuration:2.0f
                         animations:^{
                             weakSelf.alpha = 0.0;
                         }
                         completion:^(BOOL finished) {
                             [weakSelf removeFromSuperview];
                         }];
    };
    
    //要在makeKeyAndVisible之后调用才有效
    [self.window addSubview:guiderVC];
}
#pragma mark - 配置IQKeyboardManager
- (void)configurationIQKeyboard
{
//    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
//    manager.shouldResignOnTouchOutside = YES;
//    manager.shouldToolbarUsesTextFieldTintColor = YES;
//    manager.enableAutoToolbar = NO;
    
    [[IQKeyboardManager sharedManager]setKeyboardDistanceFromTextField:0];
}

#pragma mark - 检测网络
-(BOOL) isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            //NSLog(@"notReachable");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            //NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            //NSLog(@"3G");
            break;
    }
    
    if (!isExistenceNetwork) {//没网
        [MBProgressHUD hideHUD];
        [MBProgressHUD hideHUD];
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络异常" time:1.5];
       
        
        return 0;
        
    }
    return isExistenceNetwork;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
   
}


- (void)applicationWillEnterForeground:(UIApplication *)application {

}


- (void)applicationDidBecomeActive:(UIApplication *)application {

    
}


- (void)applicationWillTerminate:(UIApplication *)application {

    
    [self saveContext];
}

void UncaughtExceptionHandler(NSException *exception) {
    //获取异常信息
    NSArray *callStack = exception.callStackSymbols;
    NSString *reason = exception.reason;
    NSString *name = exception.name;
    NSString *content = [NSString stringWithFormat:@"=======错误异常报告=======\nname:%@\nreason:%@\ncallStackSymbols:\n%@", name, reason, [callStack componentsJoinedByString:@"\n"]];
    
    //发送异常信息至开发者邮件
    NSMutableString *mailURLStr = [NSMutableString stringWithString:@"mailto:3456384005@qq.com"];
    [mailURLStr appendString:@"?subject=程序异常崩溃，请配合发送异常报告，谢谢合作！"];
    [mailURLStr appendFormat:@"&body=%@", content];
    
    NSString *mailPath = [mailURLStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  //  NSString *mailStr = [mailPath stringByRemovingPercentEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailPath]];
    
    
}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {

    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"PropertyMananger"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {

        
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}
#pragma mark - 设置极光推送
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [self application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    DLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
    [self application:application didFailToRegisterForRemoteNotificationsWithError:error];
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
#endif
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    [self application:application didReceiveLocalNotification:notification];
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    [self jpushNotificationCenter:center willPresentNotification:notification withCompletionHandler:completionHandler];
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    [self jpushNotificationCenter:center didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
}
#endif

@end
